import {filter} from '@holyhigh/func.js';
import {includes, map, remove, slice} from '@holyhigh/func.js/collection';
import {indexOf, substring} from '@holyhigh/func.js/string';
const qs = require('qs');
import Mock from 'mockjs';
const Random = Mock.Random;

const dataList = [];
for (let i=0; i<30; i++) {
  dataList.push({
    id: Random.guid(),
    email: Random.email(),
    uname: Random.cname(),
    ip: Random.ip(),
    domain: Random.domain(),
  });
}

Mock.mock(/.+/, 'get', function(options) {
  // 模拟分页
  const search = substring(options.url, indexOf(options.url, '?')+1 );
  const o = qs.parse(search);
  const keyword = o.keyword;

  const start = parseInt(o.pageSize) * (parseInt(o.currentPage)-1);
  const rs = slice(filter(dataList, (d)=>{
    if (!keyword) return true;
    return includes(d.email, keyword) ||
    includes(d.uname, keyword) ||
    includes(d.ip, keyword) ||
    includes(d.domain, keyword);
  }), start, start+parseInt(o.pageSize));

  return {rows: rs, total: dataList.length};
});

Mock.mock(/.+/, 'post', function(options) {
  dataList.push({
    id: Random.guid(),
    email: Random.email(),
    uname: Random.cname(),
    ip: Random.ip(),
    domain: Random.domain(),
  });
});

Mock.mock(/.+/, 'delete', function(options) {
  const rows = JSON.parse(options.body);
  remove(dataList, (item)=>includes(map(rows, (r)=>r.id), item.id));
});
